<?php

namespace App\Package\Message;

use GuzzleHttp\Client;
use Illuminate\Support\Facades\Cache;

/**
 * 短信服务
 *
 * Date: 10/04/2018
 * @author George
 * @package App\Package\Message
 */
class Message
{
	/**
	 * 发送验证码
	 *
	 * Date: 10/04/2018
	 * @author George
	 * @param $mobile
	 * @param $code
	 * @return \SimpleXMLElement
	 * @throws \Psr\SimpleCache\InvalidArgumentException
	 */
	public function code($mobile, $code)
	{
		$content = "您的验证码是：{$code}。请不要把验证码泄露给其他人。";
		$response = $this->send($mobile, $content);

		if ((int) $response->code === 2) {
			$this->cache($mobile, $code);
		}

		return $response;
	}

	/**
	 * 发送短信
	 *
	 * Date: 10/04/2018
	 * @author George
	 * @param $mobile
	 * @param $content
	 * @return \SimpleXMLElement
	 */
	public function send($mobile, $content)
	{
		$client = new Client();
		$request = $client->post(config('system.sms.url'), [
			'form_params' => [
				'account' => config('system.sms.account'),
				'password' => config('system.sms.password'),
				'mobile' => $mobile,
				'content' => $content
			]
		]);
		return simplexml_load_string($request->getBody());
	}

	/**
	 * 校验验证码是否正确
	 *
	 * Date: 10/04/2018
	 * @author George
	 * @param $mobile
	 * @param $code
	 * @return bool
	 */
	public function verification($mobile, $code): bool
	{
		return $code === Cache::pull("verification:$mobile");
	}

	/**
	 * Date: 10/04/2018
	 * @author George
	 * @param $mobile
	 * @param $code
	 * @throws \Psr\SimpleCache\InvalidArgumentException
	 */
	private function cache($mobile, $code)
	{
		Cache::set("verification:$mobile", $code, config('system.sms.limit'));
	}
}
